/**
 * 
 */
package stc.skymobi.jcr;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.jcr.observation.EventIterator;
import javax.jcr.observation.EventListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author hp
 *
 */
public class InvokeMethodEventListener implements EventListener {

    private static final Logger logger = LoggerFactory.getLogger(InvokeMethodEventListener.class);
    
	private	Object	target;
	private	String	methodName;
	private	Method	method = null;
	
	private	void genMethod() {
		if ( null != target && null != methodName ) {
			try {
				method = target.getClass().getMethod(methodName);
				
				if ( null == method ) {
					logger.error("genMethod: can't get method for [" + target + "]." + methodName);
					throw new RuntimeException("can't get method for [" + target + "]." + methodName);
				}
			} catch (SecurityException e) {
				logger.error("genMethod:", e);
			} catch (NoSuchMethodException e) {
				logger.error("genMethod:", e);
			}
		}
	}
	
	/* (non-Javadoc)
	 * @see javax.jcr.observation.EventListener#onEvent(javax.jcr.observation.EventIterator)
	 */
	public void onEvent(EventIterator arg0) {
		if ( null != method ) {
			try {
				if ( logger.isDebugEnabled() ) {
					logger.debug("onEvent: before invoke " + method);
				}
				method.invoke(target);
				if ( logger.isDebugEnabled() ) {
					logger.debug("onEvent: after invoke " + method);
				}
			} catch (IllegalArgumentException e) {
            	logger.error("onEvent:", e);
			} catch (IllegalAccessException e) {
            	logger.error("onEvent:", e);
			} catch (InvocationTargetException e) {
            	logger.error("onEvent:", e);
			}
		}
	}

	public Object getTarget() {
		return target;
	}

	public void setTarget(Object bean) {
		this.target = bean;
		genMethod();
	}

	public String getMethod() {
		return methodName;
	}

	public void setMethod(String methodName) {
		this.methodName = methodName;
		genMethod();
	}

}
